import json
import subprocess

# 指定笔记本文件名和单元编号
notebook_filename = r'D:\workspace\edit\分享课程\c语言基础\数据结构-list\test\Untitled1.ipynb'
cell_index = -1  # 假设你想要导出第二个单元，单元编号从0开始 
e_index = [0] # 公用模块

# 读取笔记本内容
with open(notebook_filename, 'r', encoding='utf-8') as f:
    nb = json.load(f)

for i, cell in enumerate(nb['cells']): 
    if i in e_index: continue
    # 提取指定单元的代码
    cell_code = cell['source']
    ccs = []
    for l in cell_code:
        if l.startswith('%%'):
            ccs.append('# '+ l)
        else:
            ccs.append(l)
    # continue       
    # 将代码写入 Python 文件
    with open(f'cell_{i}.py', 'w', encoding='utf-8') as f:
        for kc in e_index:
            t = nb['cells'][kc]['source']
            f.write(''.join(t))
            f.write('\n')
        f.write(''.join(ccs))
    print(f'已导出单元{i}的代码到 cell_{i}.py / {len(nb["cells"])}')
    # 执行 Python 文件
    subprocess.run(['manim', f'cell_{i}.py'])

